<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="订单编号：" prop="orderCode">
        <el-input v-model="query.orderCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="客户名称：" prop="csmName">
        <el-input v-model="query.csmName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="联系方式：" prop="contactPhone">
        <el-input v-model="query.contactPhone" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: false,
            placeholder: '请选择责任机构',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item label="配送员：" prop="ownerId">
        <el-select v-model="query.ownerId" collapse-tags :loading="$loadingPlugin.getOwnersList" style="width: 100%;" filterable placeholder="请选择" clearable>
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间：" prop="time" :table-form-merge="2">
        <el-date-picker
          v-model="query.time"
          type="datetimerange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="true"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      stripe
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
    />
    <csm-detail
      ref="csmDetail"
      :parent-fetch-data="search"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
  </div>
</template>

<script>
  import {
    queryMap,
    queryExportDomain,
    csDeliverUserList,
    selectOvertime,
    exportOvertime
  } from '@/api'
  import { parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import OrderDetail from '../../orderCenter/orderManage/components/OrderDetails'
  import dayjs from 'dayjs'
  export default {
    name: '',
    components: { CsmDetail, OrderDetail },
    data() {
      return {
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方式枚举
        transactorList: [], // 处理人列表
        orderStatusMap: [],
        orderFlagMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderSourceMap: [],
        treeData: [],
        ownersList: [],
        orderTypeOption: [],
        query: {
          orderCode: '',
          csmName: '',
          contactPhone: '',
          ownerId: null,
          transactId: null,
          time: [parseTime(new Date(), '{y}-{m}-{d} 00:00:00'), parseTime(new Date(), '{y}-{m}-{d} 23:59:59')],
          transactTime: '',
          transactTimeEnd: '',
          sort: ''
        },
        tableData: {
          data: [],
          column: [
            {
              type: 'index',
              align: 'center'
            },
            {
              prop: 'orderCode',
              label: '订单编号',
              width: 180,
              render: (h, { row }) => (
                row.orderCode ? <el-link underline={false} onClick={() => this.showOrder(row)}>
                  {row.orderCode}
                </el-link> : <span>{row.orderCode}</span>
              )
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              width: 180,
              render: (h, { row }) => (
                row.csmCode ? <el-link underline={false} onClick={() => this.showCsm(row)}>
                  {row.csmCode}
                </el-link> : <span>{row.csmCode}</span>
              )
            },
            {
              prop: 'csmName',
              label: '客户名称',
              width: 220,
              showOverflowTooltip: true
            },
            {
              prop: 'contactPhone',
              label: '联系电话',
              width: 120
            },
            {
              prop: 'transactTime',
              label: '下单时间',
              width: 180,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'appointmentDt',
              label: '预约时间',
              minWidth: 200,
              render: (h, { row }) => {
                return (
                  <div>
                    {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(row.appointmentDt, '{y}-{m}-{d}') : parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                  </div>
                )
              }
              // render: (h, { row }) => <span>{ row.appointmentDt && parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'signDt',
              label: '送达时间',
              width: 180,
              render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'intSpare4',
              label: '超时时间',
              width: 100,
              render: (h, { row }) => {
                if (row.intSpare4) {
                  let h = Math.floor(row.intSpare4 / 60)
                  let m = row.intSpare4 % 60
                  // var s=v-60*h-60*m;
                  if (h < 10) h = '0' + h
                  if (m < 10) m = '0' + m
                  return <span>{ h + ':' + m }</span>
                }
                return <span></span>
              }
            },
            {
              prop: 'orgName',
              label: '所属机构',
              width: 150,
              showOverflowTooltip: true
            },
            {
              prop: 'ownerName',
              label: '配送员',
              width: 180
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    async created() {
      await this.getTreeData()
      this.getExportDomain()
      this.queryOptionsMap()
      this.$refs.lbTable.fetch({ currentPage: 1 })
    },
    methods: {
      // 查询字典枚举
      async queryOptionsMap() {
        const [res4, res5, res6, res7, res8, res9] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.orderStatusMap = res6.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res7.data // 订单类型
        this.payStatusMap = res8.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderSourceMap = res9.data // 订单来源
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.getOwnersList(value.orgId)
      },
      // 清空所属机构
      closeTree(v) {
        this.ownersList = []
        this.query.ownerId = null
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              if (key === 'time') {
                if (obj['time'].length > 0) {
                  query['transactTime'] = dayjs.utc(this.query.time[0]).format()
                  query['transactTimeEnd'] = dayjs.utc(this.query.time[1]).format()
                }
              } else {
                query[key] = obj[key]
              }
            }
          }
        }
        delete query.time
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          paramJson: { ...this._getQuery(this.query) },
          pageIndex: currentPage,
          pageSize
        }
        const res = await selectOvertime(query)
        this.tableData.data = res.data.rows
        this.tableData.total = res.data.total
      },
      // 获取所有配送员
      async getOwnersList(org) {
        // const b = this.corpSettingData.sp1 >> 2 & 0x01
        // const res = await queryOwnersList({
        //   orgId: org || -1,
        //   corpparm1: b
        // })
        const res = await csDeliverUserList({ deliveryOrgId: org })
        this.ownersList = res.data
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm('确定导出数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.tableData.column))
          list.shift()
          const value = {}
          await list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const query = {
            paramInfo: { ...this._getQuery(this.query) },
            kv: value
          }
          await exportOvertime(query).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      async showOrder(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      async showCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style scoped lang="scss">
  // /deep/.el-link.el-link--default {
  //   color: #01999F;
  // }
  // /deep/.el-link.el-link--default:hover {
  //   color: #01999F;
  // }
</style>
